<script setup lang="ts">
import { ref, nextTick, onMounted } from 'vue'
// import { getRoleMenuList } from '../../api/roles'
import { menusAll } from '@/api/interface/web/menus'
import { dictionaryAll } from '@/api/interface/common/dictionary'
import { rolesMenusList } from '@/api/interface/web/roles'
interface Props {
  roleId: string | null
}

const { roleId } = defineProps<Props>()

const fullscreenLoading = ref(false)

const treeRef = ref()
const tree = ref<any>([])
const checkStrictlyFlg = ref(true)
const checkKeys = ref<any>([])

const getCheckKeys = async () => {
  return new Promise((resolve: any) => {
    rolesMenusList({ roleId }).then((res: any) => {
      checkKeys.value = res.map((item: any) => item.menuId)
      nextTick(() => {
        checkStrictlyFlg.value = false
      })
      resolve(res)
    })
  })
}

const getMenuTree = async () => {
  return new Promise((resolve: any) => {
    menusAll({ status: '1' }).then((res: any) => {
      tree.value = res
      formatterTree(tree.value)
      resolve(res)
    })
  })
}

const formatterTree = (data: any) => {
  data.forEach((v: any) => {
    typeDictionarys.value.forEach((v2: any) => {
      if (v2.value == v.type) {
        v.typeName = v2.label
      }
    })
    if (v.children && v.children.length) {
      formatterTree(v.children)
    }
  })
}

const typeDictionarys: any = ref([])
const dictionaryAllFun = () => {
  return new Promise((resolve: any) => {
    dictionaryAll({ type: '1' }).then((res: any) => {
      typeDictionarys.value = res
      resolve(res)
    })
  })
}

const getInit = async () => {
  fullscreenLoading.value = true
  await dictionaryAllFun()
  await getMenuTree()
  await getCheckKeys()
  fullscreenLoading.value = false
}

onMounted(() => {
  getInit()
})

const submitForm = () => {
  const checkedNodes = treeRef.value.getCheckedNodes(false, true)
  const result = checkedNodes.map((item: any) => {
    return item
  })
  return result
}

defineExpose({
  submitForm,
})
</script>

<template>
  <div v-loading="fullscreenLoading" class="tree-warpper">
    <el-tree
      ref="treeRef"
      :default-checked-keys="checkKeys"
      :data="tree"
      show-checkbox
      default-expand-all
      :expand-on-click-node="false"
      node-key="id"
      :check-strictly="checkStrictlyFlg"
    >
      <template #default="{ data }">
        <span class="custom-tree-node">
          <span>{{ data.name }} - {{ data.typeName }}</span>
        </span>
      </template>
    </el-tree>
  </div>
</template>

<style lang="scss" scoped>
.tree-warpper {
  min-height: 100%;
}
</style>
